//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by yang on 15/11/10.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {
    //UserAccount属性
    var account : UserAccount?
    override init() {
        account = UserAccount.loadAccount()
    }
    //判断用户是否已经登陆
    var userLogin:Bool{
    return account?.access_token != nil
    }
    var tooken: String?{
        return account?.access_token
    }
    var userName: String?{
        return account?.name
    }
    var userHeadURL : NSURL?{
    return NSURL(string: (account?.avatar_large ?? ""))
    }
    //获取授权过的Access Token(POST)
    func loadAccessToken(code:String,finished:(error:NSError?) -> ()){
        let urlString = "oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
      NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
        if error != nil {
            finished(error:error)
            return
        }
        let account = UserAccount(dict: dict!)
        self.loadUserInfo(account, finished: finished)
        
    }
}
    //获取用户信息(GET)
    private func loadUserInfo(account : UserAccount,finished:(error:NSError?) -> ()){
        let urlString = "2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
            finished(error: error)
             return
            }
            account.avatar_large = dict!["avatar_large"] as?String
            account.name = dict!["name"] as?String
            account.saveAccount()
            finished(error: nil)
        }
    }

}
